package app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import linguistic.Quantifier;
import linguistic.Variable;

import summaries.Generator;
import summaries.Results;
import summaries.Summary;
import utils.ConfigReader;

public class Application {

	public static void main(String[] args) {
		System.out.println("Application start: " + new Date());
		
		// Load sqlite engine
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {}
		
		// Create configuration object instance
		Configuration.getInstance();
		
		// Create configuration reader object
		ConfigReader reader = new ConfigReader();
		reader.setFilename("config.xml");
		reader.start();
		
		// Read defined objects from GUI
		ObjectReader objects = new ObjectReader();
		String input_file = "";
		String output_file = "wyniki.csv";
		if (args.length == 0) {
			input_file = "objects_interval.csv";
		} else {
			input_file = args[0];
		}
		objects.createFromFile(input_file);
		
	
		// Create database connection
		Database db = new Database();
		db.setDatabaseFile(Configuration.getInstance().getDatabaseFile());
		db.connect();
		
		// Copy all tuples from databse to local variable
		List<Map<String, Double>> tuples = db.getAllTuples("games");
		
		// Create summaries generator and append quantifiers and linguistic variables
		Generator generator = new Generator();
		for (Quantifier q : objects.getQuantifiers()) {
			generator.addQuantifier(q);
		}
		for (Variable v : objects.getVariables()) {
			generator.addVariable(v);
		}
		
		// Execute generator
		generator.generate();
		
		List<Summary> summaries = generator.getSummaries();
		List<String> lines = new ArrayList<>();
		
		// And finally compute quality measures for all summaries generated by generator
		System.out.println("T1 \t T2 \t T3 \t T4 \t T5 \t T6 \t T7 \t T8 \t T9 \t T10 \t T11 \t T");
		for (Summary summary : summaries) {
			summary.setTuples(tuples);
			summary.qualityMeasures();
			
			Results results = summary.getResults();
			String line = results.getLineForFile();
			lines.add(line);
			System.out.println(results + " \t| " + summary.getText());
		}
		
		// Save results to temporary file which gonna be read by GUI application
		try {
			FileWriter fstream = new FileWriter(output_file + ".tmp", true);
			BufferedWriter out = new BufferedWriter(fstream);
			for (String line : lines) {
				out.write(line);
			}
			out.close();
		} catch (Exception e) {}
		
		// Move file to it's real path
		File file = new File(output_file + ".tmp");
		file.renameTo(new File(output_file));
		
		
		System.out.println(input_file + " ===> " + output_file);	
		System.out.println("Application stop: " + new Date());
	}
}
